/**
 * Created by lixiaodi on 2018/9/27 0027.
 */

mini.parse();
var grid = mini.get("datagrid1");
var tree = mini.get("tree1");
//按钮
var addBtn = mini.get('addBtn');
var editBtn = mini.get('editBtn');
var removeBtn = mini.get('removeBtn');
var topBtn = mini.get('topBtn');
var bottomBtn = mini.get('bottomBtn');
//初始化
$(function(){
	//加载菜单树结构
    $.ajax({
        url: ajaxUrl + "/TreeController/MoMeList.do",
        type:"post",
        success: function (data) {
            tree.setData(data.treeDate);
        },
        error:function(data){
            mini.alert(data.message);
        }
    });
    //按钮禁用
    //addBtn.disable();
    editBtn.disable();
    removeBtn.disable();
	topBtn.disable();
	bottomBtn.disable();
});
//加载数据表数据
//grid.load(ajaxUrl + "/menus/list.do");
//grid.sortBy("createtime", "desc");                  //排序
var url = bootPATH + "../frame/frame1/pages/";        //路径前缀
var menu = new ColumnsMenu(grid);
//点击树节点的时候
tree.on("nodeselect", function (e) {
    //被选中得节点
    var selecNode = e.node;
    ajaxBack(selecNode);
});
//选中行事件
function selectEvent(){
	var row = grid.getSelected();
	if(row.menuIsPreset == '是'){
		editBtn.disable();
		removeBtn.disable();
	}else{
		editBtn.enable();
		removeBtn.enable();
	}
}
//增加
function add() {
    var selectNode = tree.getSelectedNode();
    console.log(selectNode,'选择的节点');
    if(selectNode){
    	//存放父节点id的对象
        var parNodeObj = {};
        if(selectNode.id.substring(0,2) == "me"){
            //得到被选择节点的所有父节点
            var parNode = tree.getAncestors(selectNode);
            //得到菜单那id和模块id
            parNodeObj.menusId = selectNode.pk;
            for(var i = 0; i < parNode.length; i++){
                if(parNode[i].id.substring(0,2) == "mo"){
                    parNodeObj.modularId = parNode[i].pk;
                    parNodeObj.parMenusId = "";
                }else if(parNode[i].id.substring(0,2) == "me"){
                    parNodeObj.parMenusId = parNode[i].pk;
                }
            }
        }else if(selectNode.id.substring(0,2) == "mo"){
            parNodeObj.menusId = "";
            parNodeObj.parMenusId = "";
            parNodeObj.modularId = selectNode.pk;
        }
        mini.open({
            url: url +"alertBox/menusWindow.html",
            title: "新增菜单", width: 600, height: 400,
            onload: function () {
                var iframe = this.getIFrameEl();
                var data = {
                    action: "new",
                    parentMenuText: selectNode.text,
                    parentText : selectNode.text,
                    parentNodes : parNodeObj
                };
                iframe.contentWindow.SetData(data);
            },
            ondestroy: function (action) {
            	refresh();
            }
        });
    }else{
    	mini.alert('请先选择左侧菜单');
    }
}
//编辑
function edit() {
    var row = grid.getSelected();
    if (row) {
        mini.open({
            url: url +"alertBox/menusWindow.html",
            title: "编辑菜单", width: 600, height: 400,
            onload: function () {
                var iframe = this.getIFrameEl();
                var data = { action: "edit", id: row.menuId };
                iframe.contentWindow.SetData(data);
            },
            ondestroy: function (action) {
            	refresh();
            }
        });

    } else {
        mini.alert("请选中一条记录");
    }

}
//删除
function remove() {
    var rows = grid.getSelecteds();
    if (rows.length > 0) {
        mini.confirm("确定删除选中记录？","系统提示",function(action){
            if (action == "ok"){
                var ids = [];
                for (var i = 0, l = rows.length; i < l; i++) {
                    var r = rows[i];
                    ids.push(r.menuId);
                }
                var id = ids.join(',');
                grid.loading("操作中，请稍后......");
                $.ajax({
                    url: ajaxUrl + "/menus/deleteMenus.do?menuId=" + id,
                    type:"post",
                    success: function (data) {
                    	if(data.state == "error"){
                    		grid.unmask();
                    		mini.alert(data.message);
                    	}else{
                    		refresh();
                    	}
                    },
                    error: function () {
                        mini.alert('失败');
                    }
                });
            }
        })
    } else {
        mini.alert("请选中一条记录");
    }
}
//顺序调整：向上一行
function topChange(){
	var topRow = grid.getSelected();
	if(topRow){
		var menuIdVal = topRow.menuId;
		$.ajax({
			type : 'post',
			url  : ajaxUrl + '/menus/lastMenus.do',
			data : {
				menuId : menuIdVal
			},
			success : function(data) {
				if (data.state == 'success') {
					var selectNode = tree.getSelectedNode();
					ajaxBack(selectNode,topRow);
				}else{
					mini.alert(data.message);
				} 
			}
		})
	}else{
		mini.alert('请选择要移动的行');
	}
}

//顺序调整：向下一行
function bottonChange(){
	var bottomRow = grid.getSelected();
	if(bottomRow){
		var menuIdVal = bottomRow.menuId;
		$.ajax({
			type : 'post',
			url  : ajaxUrl + '/menus/nextMenus.do',
			data : {
				menuId : menuIdVal
			},
			success : function(data){
				if(data.state == 'success'){
					var selectNode = tree.getSelectedNode();
					ajaxBack(selectNode,bottomRow);
				}else{
					mini.alert(data.message);
				}
			},
			error : function(message){
				mini.alert(message);
			}
		})
	}else{
		mini.alert('请选择要移动的行');
	}
}
//查询
function search() {
    var key = mini.get("key").getValue();
    $.ajax({
        url: ajaxUrl + "/DepartmentController/getListByParam.do",
        type:"post",
        datatype:"json",
        data:{
            departmentName:key
        },
        success: function (data) {
            grid.setData(data.data)
        },
        error: function () {
            mini.alert("失败");
        }
    });
}
//回车查询
function onKeyEnter(e) {
    search();
}
//数据表刷新
function refresh(){
    var selectNode = tree.getSelectedNode();
    ajaxBack(selectNode);
}
//树刷新
function treeRefresh(){
    $.ajax({
        url: ajaxUrl + "/TreeController/MoMeList.do",
        type:"post",
        success: function (data) {
            tree.setData(data.treeDate);
        },
        error:function(data){
            mini.alert("失败");
        }
    });
}
//请求点击节点以后数据
function ajaxBack(selecNode,Row){
    if (selecNode) {
        $.ajax({
            url : ajaxUrl + "/menus/queryListByPid.do",
            type : "POST",
            data : {
                id : selecNode.pk,
                types : selecNode.id.substring(0,2)
            },
            success : function(data){
            	var menusData = data.menus;
                if(menusData){
                	if(menusData.length > 0){
                		for(var i = 0; i < menusData.length; i++){
                			//日期格式转换
                			if(menusData[i].createDate){
                				menusData[i].createDate = formatDate(menusData[i].createDate);
                			}
                			//是否系统预制
                			menusData[i].menuIsPreset = menusData[i].menuIsPreset == 1 ? '是' : '否';
                		}
                		grid.setData(menusData);
                		//按钮启用
                		//addBtn.enable();
                		editBtn.enable();
                		removeBtn.enable();
                		topBtn.enable();
                		bottomBtn.enable();
                		//重新选中行（顺序移动时执行）
                		if(Row){
                    		grid.select(Row,true);
                    	}
                	}
                }else{
                    showTips(selecNode.text);
                    grid.setData(data.menus);
                }

            },
            error : function(data){
                mini.alert(data.msg);
            }
        })
        //grid.load({ dept_id: selecNode.pk });
    } else {
        grid.setData([]);
        grid.setTotalCount(0);
    }
}
////请求顺序调整
//function sortChange(){
//	//得到被选中的行
//	var row = grid.getSelected();
//	if(row){
//		$.ajax({
//			url : '',
//			type : 'POST',
//			success : function(data){
//				//调整完毕重新刷新数据表
//				refresh();
//			},
//			error : function(data){
//				console.log('失败');
//			}
//		})
//	}else{
//		mini.alert('请选择需要调整顺序的行');
//	}
//}